package com.shihan.rabbitmq.demo.controller;

import com.shihan.rabbitmq.demo.constant.RabbitMQInfo;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;

/**
 * @Description
 * @Author shihan
 * @Date 2020/12/26 22:23
 * @Version 1.0
 */
@RestController
@RequestMapping("/rabbit")
public class RabbitMQController {

    // 自动注入 AmqpTemplate 或 RabbitTemplate 即可进行消息的发布或监听
    @Autowired
    private AmqpTemplate rabbitTemplate;

    @RequestMapping("/push/{message}")
    public String publishMessageToMQ(@PathVariable("message") String message) throws UnsupportedEncodingException {

        MessageProperties messageProperties = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .setContentEncoding("utf-8")
                .setHeader("hKey", "hValue")
                .build();

        Message msg = MessageBuilder.withBody(message.getBytes("utf-8"))
                .andProperties(messageProperties).
                        build();

        rabbitTemplate.send(RabbitMQInfo.EXCHANGE_BOOT_DIRECT_E1,"rabbit.hello",msg);

        return "消息发布成功！";
    }


}
